package com.rainbow.support.half.message.handler.producer;

import com.rainbow.common.core.toolkit.SpringBeanUtil;
import com.rainbow.support.half.message.entity.HalfMessagePayload;
import com.rainbow.support.half.message.handler.BaseHalfMsgHandler;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.lang.NonNull;

import java.util.Collections;
import java.util.List;

/**
 * rocketMq半事务统一处理类
 * 判断事务状态,检查生产者业务数据,
 * 方便幂等处理
 * @author 傅为地
 */
public interface BaseLocalProducerHandler extends BaseHalfMsgHandler {

    /**
     * 检查事务状态
     * @param branchId 分支事务id
     * @return  本地事务执行结果
     */
    default boolean checkTransactionStatus(@NonNull String branchId){
        Integer total=SpringBeanUtil.getBean("jdbcTemplate", JdbcTemplate.class).queryForObject("select count(*) as total from rocket_mq_producer_log  where logic_delete=false and branch_id = '"+branchId+"'",Integer.class);
        return ObjectUtils.isNotEmpty(total) && total > 0;
    }

    /**
     * 查询业务类型下已经处理的生产者记录
     * 针对半事务生产者在生成分支事务id(唯一键生成)时,
     * 协助生产者做幂等处理工具
     * @param category 业务类型
     * @return  本地事务执行结果
     */
    default List<HalfMessagePayload> selectPreServiceListByCategory(@NonNull String category){
        if(StringUtils.isEmpty(category)){
            return Collections.emptyList();
        }
        return SpringBeanUtil.getBean("jdbcTemplate", JdbcTemplate.class).query("select category,expandtag from rocket_mq_producer_log  where logic_delete=false and category = '"+category+"' order by create_time desc",new BeanPropertyRowMapper<>(HalfMessagePayload.class));
    }

    /**
     * 查询业务类型下已经处理的生产者记录
     * 针对半事务生产者在生成分支事务id(唯一键生成)时,
     * 协助生产者做幂等处理工具
     * @param category 业务类型
     * @return  本地事务执行结果
     */
    default List<HalfMessagePayload> selectProducerListByCategory(@NonNull String category){
        if(StringUtils.isEmpty(category)){
            return Collections.emptyList();
        }
        return SpringBeanUtil.getBean("jdbcTemplate", JdbcTemplate.class).query("select * from rocket_mq_producer_log  where logic_delete=false and category = '"+category+"' order by create_time desc",new BeanPropertyRowMapper<>(HalfMessagePayload.class));
    }


}
